// 2025/3/9
// https://leetcode.cn/problems/diameter-of-binary-tree/description/?envType=study-plan-v2&envId=top-100-liked
// 二叉树的直径

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    public:
        pair<int, int> find(TreeNode* root)
        {
            if(root == nullptr)
                return (pair<int, int>){0, 0};
            
            pair<int, int> left = find(root->left);
            pair<int, int> right = find(root->right);
            int diameter = max(max(left.second, right.second), left.first + right.first + 1);
            return (pair<int, int>){max(left.first, right.first) + 1, diameter};
        }
    
        int diameterOfBinaryTree(TreeNode* root) {
            return find(root).second - 1;
        }
    };